<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="枪证号码" prop="gunLicenceNum">
        <el-input
          v-model="queryParams.gunLicenceNum"
          placeholder="请输入枪证号码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="持枪证有效期" prop="gunLicenceValidity">
        <el-date-picker clearable
          v-model="queryParams.gunLicenceValidity"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择持枪证有效期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['service:licence:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['service:licence:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['service:licence:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['service:licence:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="licenceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="枪证号码" align="center" prop="gunLicenceNum" />
      <el-table-column label="持枪证有效期" align="center" prop="gunLicenceValidity" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.gunLicenceValidity, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="证件管理状态" align="center" prop="licenceStatus" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['service:licence:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['service:licence:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改枪支许可证信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="licenceRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="emplyee表id" prop="employeeId"  v-show="false">
          <el-input v-model="form.employeeId" />
        </el-form-item>
    <!-- 姓名（只读）+ 选择按钮 -->
    <el-form-item label="姓名" prop="empName">
      <el-input v-model="form.empName" placeholder="请选择员工" readonly>
        <template #append>
          <el-button type="primary" @click="openEmpDlg">选择</el-button>
        </template>
      </el-input>
    </el-form-item>
        <!-- 身份证号（只读回显） -->
        <el-form-item label="身份证号">
          <el-input v-model="form.idno" readonly />
        </el-form-item>
        <el-form-item label="枪证号码" prop="gunLicenceNum">
          <el-input v-model="form.gunLicenceNum" placeholder="请输入枪证号码" />
        </el-form-item>
        <el-form-item label="持枪证有效期" prop="gunLicenceValidity">
          <el-date-picker clearable
            v-model="form.gunLicenceValidity"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择持枪证有效期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="证件图片">
          <div style="display:flex;gap:8px;align-items:center;">
            <el-upload
              :action="uploadUrl"
              name="file"
              :data="uploadData"
              :show-file-list="false"
              :headers="{ Authorization: 'Bearer ' + getToken() }"
              :before-upload="beforeUpload"
              :on-success="onUploadSuccess"
              :on-error="() => ElMessage.error('上传失败')"
              accept=".jpg,.jpeg,.png"
            >
              <el-button type="primary">选择文件</el-button>
            </el-upload>
            <el-input v-model="pickedFileName" placeholder="未选择任何文件" style="width:280px" readonly />
          </div>
        </el-form-item>
            
        <el-form-item label="图片地址" prop="photoUrl">
          <el-input v-model="form.photoUrl" placeholder="上传成功后自动填入" readonly />        
        </el-form-item>	
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="选择员工" v-model="empOpen" width="860px" append-to-body draggable 
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :show-close="false">
      <el-form :model="empQuery" inline size="small">
        <el-form-item label="姓名">
          <el-input v-model="empQuery.empName" placeholder="输入姓名" @keyup.enter="getEmpList" />
        </el-form-item>
        <el-button type="primary" @click="getEmpList">查询</el-button>
        <el-button @click="() => { empQuery.empName = '' ; getEmpList() }">重置</el-button>
      </el-form>

      <el-table :data="empList" height="420" @row-dblclick="chooseEmp">
        <el-table-column prop="empNo" label="工号" width="120" />
        <el-table-column prop="empName" label="姓名" width="140" />
        <el-table-column prop="idno" label="身份证号" width="180" />
        <el-table-column prop="employmentStatus" label="状态" width="80">
          <template #default="{ row }">
            <span v-if="Number(row.employmentStatus) === 0">在职</span>
            <span v-else>离职</span>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="empOpen=false">关 闭</el-button>
      </template>
    </el-dialog>    
  </div>
</template>

<script setup name="Licence">
import { getToken } from "@/utils/auth";
import { listLicence, getLicence, delLicence, addLicence, updateLicence } from "@/api/service/licence"
import { listEmployees} from "@/api/service/employees"
import { ElMessage } from 'element-plus'

const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/file/upload"); // 上传的图片服务器地址
const uploadData = ref({ type: "gunPermit" }); // 这个页面默认存员工证件照
function openEmpDlg() {
  empOpen.value = true
  getEmpList()
}

const pickedFileName = ref('')

function beforeUpload(file) {
  const okType = ['image/jpeg','image/jpg','image/png'].includes(file.type)
  const okSize = file.size <= 5 * 1024 * 1024
  if (!okType) ElMessage.error('仅支持 jpg/png/jpeg')
  if (!okSize) ElMessage.error('文件不能超过 5MB')
  pickedFileName.value = file.name
  return okType && okSize
  }
  
  function onUploadSuccess(res) {
    // 按后端返回：{ code:200, data:{ url, fileName } }
    if (res.code === 200) {
      form.value.photoUrl = res.data.url
      ElMessage.success('上传成功')
    } else {
      ElMessage.error(res.msg || '上传失败')
    }
  }

function getEmpList() {
  listEmployees(empQuery.value).then(res => {
    empList.value = res.rows || res.data || []
  })
}

function chooseEmp(row) {
  form.value.employeeId = row.id          // 外键
  form.value.empName    = row.empName     // 回显
  form.value.idno       = row.idno        // 回显
  empOpen.value = false
}
const { proxy } = getCurrentInstance()

const licenceList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 选择员工弹窗相关
const empOpen  = ref(false)
const empQuery = ref({ empName: '' })
const empList  = ref([])

const data = reactive({
  form: {
    id: null,
    gunLicenceNum: null,
    photoUrl:'',
    authority:'',
    remark:'',
    status:''
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    gunLicenceNum: null,
    gunLicenceValidity: null,
  },
  rules: {
    empName: [
      { required: true, message: "请选择员工姓名", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询枪支许可证信息列表 */
function getList() {
  loading.value = true
  listLicence(queryParams.value).then(response => {
    licenceList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    employeeId: null,
    gunLicenceNum: null,
    gunLicenceValidity: null,
    photoUrl: null,
    createUser: null,
    createTime: null,
    updateUser: null,
    updateTime: null,
    licenceStatus: null,
    departmentId: null,
    remark: null,
    deleted: null
  }
  proxy.resetForm("licenceRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加枪支许可证信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getLicence(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改枪支许可证信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["licenceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateLicence(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addLicence(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除枪支许可证信息编号为"' + _ids + '"的数据项？').then(function() {
    return delLicence(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('service/licence/export', {
    ...queryParams.value
  }, `licence_${new Date().getTime()}.xlsx`)
}

getList()
</script>
